<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8">
  <title>用户管理</title>
  <link rel="stylesheet" href="/pear_layui/component/pear/css/pear.css"/>
</head>
<body class="pear-container">
<div class="layui-card">
  <div class="layui-card-body">
    <form class="layui-form" action="">
      <div class="layui-form-item">
        <div class="layui-form-item layui-inline">
          <label class="layui-form-label">账号</label>
          <div class="layui-input-inline">
            <input type="text" name="account" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item layui-inline">
          <label class="layui-form-label">姓名</label>
          <div class="layui-input-inline">
            <input type="text" name="realName" class="layui-input">
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">登录</label>
          <div class="layui-input-inline">
            <select name="online" autocomplete="off" class="layui-input">
              <option value="">请选择</option>
              <option value="1">在线</option>
              <option value="0">离线</option>
            </select>
          </div>
        </div>
        <div class="layui-form-item layui-inline">
          <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-query">
            <i class="layui-icon layui-icon-search"></i>
            查询
          </button>
          <button type="reset" class="pear-btn pear-btn-md">
            <i class="layui-icon layui-icon-refresh"></i>
            重置
          </button>
        </div>
      </div>
    </form>
  </div>
</div>
<div class="layui-card">
  <div class="layui-card-body">
    <table id="user-table" lay-filter="user-table"></table>
  </div>
</div>
<!--添加和修改窗口-->
<div id="addOrUpdateWindow" style="display: none;padding: 30px;">
  <form class="layui-form" action="" id="dataFrm" lay-filter="dataFrm">
    <!-- 隐藏域，保存用户id -->
    <input type="hidden" name="id" value="">
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">账号</label>
        <div class="layui-input-block">
          <input type="text" name="account" lay-verify="required" autocomplete="off" placeholder="请输入账号"
                 class="layui-input checkAccount">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label">姓名</label>
        <div class="layui-input-block">
          <input type="text" name="realName" id="realName" lay-verify="required" autocomplete="off" placeholder="请输入姓名"
                 class="layui-input">
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
          <input type="radio" name="gender" value="1" title="男" checked>
          <input type="radio" name="gender" value="0" title="女">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label">年龄</label>
        <div class="layui-input-block">
          <input type="text" name="age" id="age" lay-verify="required|number" autocomplete="off" placeholder="请输入年龄"
                 class="layui-input">
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">电话</label>
        <div class="layui-input-block">
          <input type="text" name="phone" id="phone" lay-verify="required|phone" autocomplete="off" placeholder="请输入电话"
                 class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label">地址</label>
        <div class="layui-input-block">
          <input type="text" name="address" id="address" lay-verify="required" autocomplete="off" placeholder="请输入地址"
                 class="layui-input">
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
          <input type="password" name="password" autocomplete="off" placeholder="请输入密码，默认：000" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block">
          <input type="checkbox" checked="" value="1" name="status" lay-skin="switch" lay-filter="switchTest"
                 lay-text="可用|禁用">
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">角色</label>
      <div class="layui-input-block" id="roleField">
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">描述</label>
      <div class="layui-input-block">
        <textarea placeholder="请输入..." name="description" class="layui-textarea"></textarea>
      </div>
    </div>

    <div class="bottom">
      <div class="button-container">
        <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit="" lay-filter="doSubmit">
          <i class="layui-icon layui-icon-ok"></i>
          提交
        </button>
        <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
          <i class="layui-icon layui-icon-refresh"></i>
          重置
        </button>
      </div>
    </div>
  </form>
</div>

<script type="text/html" id="user-toolbar">
  <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"><i
          class="layui-icon layui-icon-add-1"></i>添加
  </button>
</script>
<script type="text/html" id="user-bar">
  <a class="layui-btn layui-btn-xs data-count-edit" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
  <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="remove"><i
          class="layui-icon layui-icon-delete"></i>删除</a>
</script>

<script type="text/html" id="user-status">
  <!--checked = "{{ d.status == 1 ? 'true' : 'false' }}"-->
  {{#if (d.status == 1) { }}
  <input type="checkbox" name="tableStatus" value="{{d.status}}" lay-skin="switch" lay-text="可用|禁用" lay-filter="user-status"
         checked>
  {{# }else if(d.status == 0){ }}
  <input type="checkbox" name="tableStatus" value="{{d.status}}" lay-skin="switch" lay-text="可用|禁用" lay-filter="user-status">
  {{# } }}
</script>

<script type="text/html" id="user-gender">
  {{#if (d.gender == 1) { }}
  <span title="男"><i class="layui-icon layui-icon-male"></i></span>
  {{# }else if(d.gender == 0){ }}
  <span title="女"><i class="layui-icon layui-icon-female"></i></span>
  {{# } }}
</script>

<script type="text/html" id="user-online">
  {{#if (d.online == 1) { }}
  <span><font color="#32cd32">在线</font></span>
  {{# }else if(d.online == 0){ }}
  <span><font color="#a9a9a9">离线</font></span>
  {{# } }}
</script>

<script type="text/html" id="user-createTime">
  {{layui.util.toDateString(d.createTime, 'yyyy-MM-dd')}}
</script>

<script src="/pear_layui/component/layui/layui.js"></script>
<script src="/pear_layui/component/pear/pear.js"></script>
<script>
  layui.use(['table', 'form', 'jquery', 'common'], function () {
    let table = layui.table;
    let form = layui.form;
    let $ = layui.jquery;
    let common = layui.common;
    //定义添加和修改的url 以及弹出层对象
    let url, mainIndex;

    let cols = [
      [/*{
							type: 'checkbox'
						},*/
        {
          field: 'id',
          hide: true
        },
        {
          title: '账号',
          field: 'account',
          align: 'center',
          width: 90,
          /*fixed: 'left'*/
        },
        {
          title: '姓名',
          field: 'realName',
          align: 'center'
        },
        {
          title: '性别',
          field: 'gender',
          align: 'center',
          width: 80,
          templet: '#user-gender'
        },
        {
          title: '年龄',
          field: 'age',
          align: 'center',
          width: 80,
          sort: true,
          templet: '#user-sex'
        },
        {
          title: '电话',
          field: 'phone',
          align: 'center'
        },
        {
          title: '地址',
          field: 'address',
          align: 'center',
        },
        {
          title: '创建',
          field: 'gmtCreate',
          width: 180,
          sort: true,
          align: 'center',
        },
        {
          title: '登录',
          field: 'online',
          align: 'center',
          width: 80,
          templet: '#user-online'
        },
        {
          title: '状态',
          field: 'status',
          align: 'center',
          templet: '#user-status'
        },
        {
          title: '操作',
          toolbar: '#user-bar',
          align: 'center',
          width: 160
        }
      ]
    ]

    /**
     * 渲染表格数据
     */
    let tableIns = table.render({
      elem: '#user-table',
      url: '/user/findUser',
      page: true,
      limit: 8,
      limits: [8, 16, 32, 64, 128, 256, 512],
      cols: cols,
      skin: 'line',
      toolbar: '#user-toolbar',
      defaultToolbar: [{
        layEvent: 'refresh',
        icon: 'layui-icon-refresh',
      }, 'filter', 'print', 'exports'],
      done: function (res, curr, count) {
        //判断当前页码是否是大于1并且当前页的数据量为0
        if (curr > 1 && res.data.length == 0) {
          var pageValue = curr - 1;
          //刷新数据表格的数据
          tableIns.reload({
            page: {curr: pageValue}
          });
        }
      }
    });

    //初始化角色信息
    initRoleField();

    //行工具栏
    table.on('tool(user-table)', function (obj) {
      if (obj.event === 'remove') {
        window.remove(obj);
      } else if (obj.event === 'edit') {
        window.edit(obj);
      }
    });
    /**
     * 表头工具栏
     */
    table.on('toolbar(user-table)', function (obj) {
      if (obj.event === 'add') {
        window.add();
      } else if (obj.event === 'refresh') {
        window.refresh();
      }
    });

    /**
     * 根据条件筛选表格数据
     */
    form.on('submit(user-query)', function (data) {
      table.reload('user-table', {
        where: data.field,
        page: {
          curr: 1
        }
      })
      return false;
    });

    form.on('switch(user-status)', function (obj) {
      //当前元素
      let data = $(obj.elem);
      //遍历父级tr，取第一个，然后查找第一个td，取id值
      let id = data.parents('tr').first().find('td').eq(0).text();
      let selectStatus, msg;
      if (obj.elem.checked) {
        selectStatus = 1;
        msg = '<font color="#32cd32">可用</font>';
      } else {
        selectStatus = 0;
        msg = '<font color="#a9a9a9">禁用</font>';
      }
      $.post("/user/updateStatus", {'id': id, 'status': selectStatus}, function (result) {
        if (result.success) {
          layer.tips('已修改为：' + msg, obj.othis,/*{tips:4}*/);
        } else {
          layer.tips('修改失败');
        }
      }, 'json');
    });

    //打开添加窗口
    window.add = function () {
      let loadIndex = layer.load(1);
      mainIndex = layer.open({
        type: 1,
        title: '新增用户',
        shade: 0.1,
        area: ['700px', '520px'],//宽高
        content: $('#addOrUpdateWindow'),
        //成功打开面板函数
        success: function () {
          layer.close(loadIndex);
          //清空表单数据
          $('#dataFrm')[0].reset();
          $("input[name='password']").attr('type','password');
          $("input[name='password']").attr('disabled', false).removeClass('layui-disabled');
          setAddRoleField();
          //设置表单提交的url
          url = '/user/save';
          $('.checkAccount').css('border', '1px solid #E6E6E6');
        }
      });
    };

    //打开编辑窗口
    window.edit = function (obj) {
      //给用户所属角色赋值
      setEditRoleField(obj.data.id);
      let loadIndex = layer.load(1);
      mainIndex = layer.open({
        type: 1,
        title: '编辑用户',
        shade: 0.1,
        area: ['700px', '520px'],//宽高
        content: $('#addOrUpdateWindow'),
        //成功打开面板函数
        success: function () {
          layer.close(loadIndex);
          //禁用修改密码选项
          $("input[name='password']").attr('disabled',true).addClass('layui-disabled');
          //清空表单数据
          $('#dataFrm')[0].reset();
          //设置表单提交的url
          url = '/user/edit';
          //给修改表单赋值
          $.post("/user/findById/" + obj.data.id,function (result) {
            form.val('dataFrm', result);
            $("input[name='password']").attr('type','text').val('不可操作');
            $('.checkAccount').css('border', '1px solid #E6E6E6');
          },'json');
        }
      });
    };

    //监听表单提交事件
    form.on('submit(doSubmit)', function (data) {
      let loadIndex = layer.load(1);
      $.post(url, $('#dataFrm').serialize(), function (result) {
        layer.close(loadIndex);
        if (result.exist) {
          layer.msg(result.message, {icon: 0});
          $('.checkAccount').css('border', '1px solid red');
        } else {
          if (result.success) {
            layer.msg(result.message, {icon: 1,});
            layer.close(mainIndex);//关闭窗口
            tableIns.reload();//刷新表格
          } else {
            layer.msg(result.message, {icon: 2, anim: 6});
          }
        }
      }, 'json');
    });

    //初始化角色信息
    function initRoleField() {
      $.post("/role/getRole", function (result) {
        if (result.length > 0) {
          let html = '';
          for (let e of result) {
            html += `
									<input type="checkbox" name="role" lay-skin="primary" value="` + e.id + `" title="` + e.name + `">
								`;
          }
          $('#roleField').html(html);
        }
      }, 'json');
    }

    //设置添加时的role信息
    function setAddRoleField() {
      let roles = $("[name='role']");
      roles.each(function (i) {
        //默认选中"用户"的角色
        if ($(this).val() == 1) {
          $(this).prop('checked', true);
        } else {
          $(this).prop('checked', false);
        }
      });
      //form.render("checkbox");//重新渲染
    }

    ////设置编辑时的role信息
    function setEditRoleField(id) {
      $.post("/user/findRoleById/" + id, function (result) {
        if (result.length > 0) {
          for (let r of result) {
            $("input[name='role'][value='" + r.r_id + "']").prop('checked', true);
          }
        }
      }, 'json');
    }

    window.remove = function (obj) {
      layer.confirm('确定要删除账号为' + obj.data['account'] + '的用户及所属角色关系表中的数据吗？', {
        icon: 3,
        title: '提示'
      }, function (index) {
        let loadIndex = layer.load(1);
        $.post("/user/delete/" + obj.data['id'], function (result) {
          layer.close(loadIndex);
          if (result.success) {
            layer.msg(result.message, {icon: 1});
            tableIns.reload();
          } else {
            layer.msg(result.message, {icon: 2, anim: 6});
          }
        }, 'json');
        layer.close(index);
      });
    }

    window.refresh = function (param) {
      table.reload('user-table');
    };

    //如果登录名称重复 当登录名称获得焦点时改回边框样式
    $('.checkAccount').blur(function () {
      $(this).css('border', '1px solid #E6E6E6');
    });
  })
</script>
</body>
</html>
